package com.hqyj.springCloudAccount.dao;

import com.hqyj.entity.account.Resource;
import com.hqyj.entity.common.SearchBean;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
public interface ResourceDao {

    @Insert("insert into account_resource (permission,create_date) values (#{permission},#{createDate})")
    @Options(useGeneratedKeys = true, keyColumn = "id", keyProperty = "id")
    void addResource(Resource resource);

    @Update("update account_resource set permission = #{permission} where id = #{id}")
    void updateResourceByResource(Resource resource);

    @Delete("delete from account_resource where id = #{id}")
    void deleteResourceById(int id);

    @Select("select * from account_resource where id = #{id}")
    @Results(id="resourceResult", value={
            @Result(column="id", property="id"),
            @Result(column="id",property="roles",
                    javaType=List.class,
                    many=@Many(select="com.hqyj.springCloudAccount.dao.RoleDao.getRolesByResourceId"))
    })
    Resource selectResourceById(int id);

    @Select("select * from account_resource ar left join account_role_resource arr on ar.id = arr.resource_id "
            + "where arr.role_id = #{roleId}")
    List<Resource> getResourcesByRoleId(int roleId);

    @Select("<script>"
            + "select * from account_resource "
            + "<where> "
            + "<if test='keyWord != \"\" and keyWord != null'>"
            + " and (permission like '%${keyWord}%') "
            + "</if>"
            + "</where>"
            + "<choose>"
            + "<when test='orderBy != \"\" and orderBy != null'>"
            + " order by ${orderBy} ${direction}"
            + "</when>"
            + "<otherwise>"
            + " order by id desc"
            + "</otherwise>"
            + "</choose>"
            + "</script>")
    List<Resource> getResourcesBySearchBean(SearchBean searchBean);
}
